#!/usr/bin/env bash
set -e

# This script generates to code for the
# ordinal_value_is_first64bits_of_sha256 test in ordinals_test.cc.

function hash_of_fq_method_name() {
    local fq_method_name=$1
    echo -n "${fq_method_name}" | sha256sum | sed \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)\([0-7].\).*$/0x\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)8\(.\).*$/0x0\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)9\(.\).*$/0x1\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)a\(.\).*$/0x2\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)b\(.\).*$/0x3\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)c\(.\).*$/0x4\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)d\(.\).*$/0x5\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)e\(.\).*$/0x6\8\7\6\5\4\3\2\1/' \
        -e 's/^\([0-9a-f][0-9a-f]\)\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)f\(.\).*$/0x7\8\7\6\5\4\3\2\1/'
}

max_selector=31

echo "// generated by gen_ordinal_value_is_first64bits_of_sha256_test.sh"
echo "bool ordinal_value_is_first64bits_of_sha256() {"
echo "  BEGIN_TEST;"
echo ""
echo "  TestLibrary library(R\"FIDL("
echo "library a.b.c;"
echo ""
echo "protocol protocol {"
for ord in `seq 0 ${max_selector}`; do
    echo "    s${ord}();"
done
echo "};"
echo ")FIDL\");"
echo "  ASSERT_TRUE(library.Compile());"
echo ""
echo "  const fidl::flat::Protocol* iface = library.LookupProtocol(\"protocol\");"
for ord in `seq 0 ${max_selector}`; do
    fq_method_name="a.b.c/protocol.s${ord}"
    expected_hash=$(hash_of_fq_method_name "${fq_method_name}")
    echo "  EXPECT_EQ(iface->methods[${ord}].generated_ordinal64->value, ${expected_hash});"
done
echo ""
echo "  END_TEST;"
echo "}"
